from typing import Optional
from src.domain.email_pending_task import EmailPendingTask
from src.domain.email_pending_task_repository import EmailPendingTaskRepository
from src.infrastructure.mysql_connection import MySQLConnection

class EmailPendingTaskService:
    """Service layer for email pending task operations"""
    
    def __init__(self, repository: EmailPendingTaskRepository):
        self.repository = repository
    
    def create_email_pending_task(self, email_id: str, task_id: str, 
                                 email_info_json: Optional[str] = None,
                                 sop_json: Optional[str] = None,
                                 generated_reply: Optional[str] = None,
                                 action_type: Optional[str] = None,
                                 created_by: Optional[str] = None) -> int:
        """
        Create a new email pending task
        
        Args:
            email_id: Email identifier
            task_id: Task identifier
            email_info_json: Email information as JSON string (optional)
            sop_json: SOP information as JSON string (optional)
            generated_reply: Generated reply content (optional)
            action_type: Action type (optional)
            created_by: Creator identifier (optional)
            
        Returns:
            The ID of the created task
            
        Raises:
            ValueError: If required fields are missing
            Exception: If database operation fails
        """
        # Validate required fields
        if not email_id:
            raise ValueError("email_id is required")
        if not task_id:
            raise ValueError("task_id is required")
        
        # Check if task_id already exists
        existing_task = self.repository.find_by_task_id(task_id)
        if existing_task:
            raise ValueError(f"Task with task_id '{task_id}' already exists")
        
        # Create entity
        email_pending_task = EmailPendingTask(
            email_id=email_id,
            task_id=task_id,
            email_info_json=email_info_json,
            sop_json=sop_json,
            generated_reply=generated_reply,
            action_type=action_type,
            created_by=created_by or "system"
        )
        
        # Save to repository
        return self.repository.save(email_pending_task)
    
    def get_task_by_id(self, task_id: int) -> Optional[EmailPendingTask]:
        """Get an email pending task by ID"""
        return self.repository.find_by_id(task_id)
    
    def get_tasks_by_email_id(self, email_id: str) -> list:
        """Get all email pending tasks for a specific email"""
        return self.repository.find_by_email_id(email_id)
    
    def get_task_by_task_id(self, task_id: str) -> Optional[EmailPendingTask]:
        """Get an email pending task by task_id"""
        return self.repository.find_by_task_id(task_id)